package com.tofine.smarthome.common.gson;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.tofine.smarthome.model.Device;

import java.lang.reflect.Type;

/**
 * @author ddMax
 * @since 2016/6/1 15:00.
 * 说明：Gson custom serializer
 */
public class DeviceTypeAdapter implements JsonSerializer<Device>, JsonDeserializer<Device> {

    @Override
    public JsonElement serialize(Device device, Type typeOfSrc, JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("_id", device._id);
        jsonObject.addProperty("image_url", device.image);
        jsonObject.addProperty("name", device.name);
        jsonObject.addProperty("intro", device.intro);
        jsonObject.addProperty("status", device.status);
        jsonObject.addProperty("isFavorite", device.isFavorite);
        jsonObject.addProperty("category", device.category._id);
        jsonObject.addProperty("room", device.room._id);

        return jsonObject;
    }

    @Override
    public Device deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        final JsonObject jsonObject = json.getAsJsonObject();

        Device device = new Device();
        device._id = jsonObject.get("_id").getAsString();
        device.image = jsonObject.get("image_url").getAsString();
        device.name = jsonObject.get("name").getAsString();
        device.intro = jsonObject.get("intro").getAsString();
        device.status = jsonObject.get("status").getAsBoolean();
        device.isFavorite = jsonObject.get("isFavorite").getAsBoolean();

        final String categoryId = jsonObject.get("category").getAsString();
        device.setCategoryById(categoryId);
        final String roomId = jsonObject.get("room").getAsString();
        device.setRoomById(roomId);

        return device;
    }
}
